#ifndef __WN_DEVICE_H
#define __WN_DEVICE_H
#include <rtthread.h>
#include <stdint.h>
#include <stdbool.h>
#include "wn_uart.h"

#define WN_DEVICE_NAME_MAX 32
#define WN_DEVICE_ID_MAX 6
#define WN_DEVICE_SN_MAX 16
#define WN_LEN_MAX 32
#define WN_DEVICE   250

#define WN_SYSCONF_ADDR 0x0001
#define WN_SIMPLE_ADDR 0x006e
typedef struct{
    rt_uint32_t  pvTempPower;
    rt_uint32_t  acTempPower;
    float       gridFreq;
    float       sysStatus;
    rt_uint32_t  sysctlCmd;
    rt_uint32_t  pvVolReal;
    float       PvCurrReal;
    rt_uint32_t  acVolReal;
    rt_uint32_t  acCurrReal;
    float       acMosTempReal;
    rt_uint32_t  pVMosTempReal;
    rt_uint32_t  dayRunTime;
    float       dailyEnergy;

}wn_data;
typedef struct {
    char    name[WN_DEVICE_NAME_MAX];
    uint8_t device_sn[WN_DEVICE_SN_MAX];
    wn_data param_data;
    rt_uint8_t  pvCount;
    rt_uint8_t  commStatus;
    rt_uint8_t  falutCode;
    rt_uint8_t  softVer[WN_LEN_MAX];
    rt_uint8_t  hardVer[WN_LEN_MAX];
    rt_uint8_t enable;
    rt_uint8_t id; //广播id
}wn_device_t;

//寄存器结构
typedef struct{
    rt_uint16_t regStart;
    rt_uint16_t regAddr;
    rt_uint32_t regValue;
}wn_reg_t;
typedef struct{
    uint8_t sn[WN_DEVICE_SN_MAX];
}sn_set_t;
//文件传输结构
enum plc_event{
    PLC_READREGS_RESP_EVENT = 1<< 0,
    PLC_ADDWHITELIST_RESP_EVENT = 1<< 1,
    PLC_READDEVICE_RESP_EVENT = 1<<2,
};
enum devicemgr_status{
    status_init,
    status_add_whitelist,
    status_broadcost_id,
    status_normal,
    status_update_wn,
};
/**@brief     初始化设备管理任务
* @param[in]  无
* @param[out] 无
* @return     无
*/
void init_devicemgr_task();

void init_wn_task();

void handle_wn_reveivedata(uint8_t*data,  int len);
int scan_process(void*data);
int frame_check_crc(uint8_t*data,  int len);
int recv_onepacket(serial_t *serial, rt_uint8_t *recvBuf, uint32_t recvBufLen, uint32_t timeout, uint32_t tryOneDelayMs,uint32_t *sendBufLen);

wn_device_t* wn_getdevices(wn_device_t*,rt_uint32_t* size);

wn_device_t* wn_getdevice_fromSn(const char* sn);

void    wn_setdevice_fromSn(wn_device_t* device,const char* sn);
void    wn_update_field_addr(wn_device_t* device,rt_uint32_t addr,rt_uint32_t value);

rt_uint8_t wn_device_readRegs(uint8_t id,uint8_t* sn,uint16_t startReg,uint16_t regNum);
rt_uint8_t wn_device_broadcast();
rt_uint8_t wn_device_writereg(uint8_t* sn,uint16_t startReg,float value);
rt_uint8_t wn_device_writeregs(uint8_t* sn,wn_reg_t* regs,uint16_t regNum);
rt_uint8_t wn_device_readfile_error(uint8_t* sn);
rt_uint8_t wn_plc_init();

rt_uint8_t wn_device_startframe(uint8_t* sn,uint8_t file_type,uint32_t filesize,uint16_t packsize);
rt_uint8_t wn_device_dataFrame(uint8_t* sn,uint8_t file_type,uint16_t packetIndex,uint8_t* data,int dataLen);
rt_uint8_t wn_device_stopFrame(uint8_t* sn,uint8_t file_type);
#endif
